package com.ming.mallchat.common.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import com.ming.mallchat.common.websocket.domain.utils.NettyUtils;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import org.apache.commons.lang3.StringUtils;

import java.net.InetSocketAddress;
import java.util.Optional;

public class MyCollectHandler extends ChannelInboundHandlerAdapter {

    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest) msg;
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(httpRequest.getUri());
            Optional<String> tokenOptional = Optional.of(urlBuilder)
                    .map(UrlBuilder::getQuery)
                    .map(k -> k.get("token"))
                    .map(CharSequence::toString);
            //token存在则存入netty
            if (tokenOptional.isPresent()) {
                NettyUtils.setAttr(ctx.channel(),NettyUtils.TOKEN,tokenOptional.get());
            }
            httpRequest.setUri(urlBuilder.getPath().toString());
            String ip = httpRequest.headers().get("X-Real-IP");
            if (StringUtils.isBlank(ip)) {
                ip = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
            }
            NettyUtils.setAttr(ctx.channel(),NettyUtils.IP,ip);
            ctx.pipeline().remove(this);
        }
        ctx.fireChannelRead(msg);
    }
}
